package com.cneport.transfer.message.wrapper.support;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

import com.cneport.transfer.config.HeadSettingConfigure;
import com.cneport.transfer.config.HeadSettingConfigureParser;
import com.cneport.transfer.message.wrapper.HeadUnWrapperException;
import com.cneport.transfer.message.wrapper.HeadWrapperException;
import com.cneport.transfer.message.wrapper.MessageWrapper;
import com.cneport.transfer.util.Base64EncodeUtil;
import com.cneport.transfer.util.XmlParseUtil;
import com.sun.org.apache.xpath.internal.XPathAPI;

public class DxpMessageWrapperImpl implements MessageWrapper{
	java.util.concurrent.atomic.AtomicInteger wrapSuccessCount = new java.util.concurrent.atomic.AtomicInteger(0);
	java.util.concurrent.atomic.AtomicInteger wrapFailureCount = new java.util.concurrent.atomic.AtomicInteger(0);
	java.util.concurrent.atomic.AtomicInteger unWrapSuccessCount = new java.util.concurrent.atomic.AtomicInteger(0);
	java.util.concurrent.atomic.AtomicInteger unWrapFailureCount = new java.util.concurrent.atomic.AtomicInteger(0);
	ThreadLocal<Integer> count = new ThreadLocal<Integer>();
	
	private static final Log logger = LogFactory.getLog(DxpMessageWrapperImpl.class);

	private String messageType;
	
	
	private boolean isEncoded = true;
	
	
	public String wrap(String message) throws HeadWrapperException{
		HeadSettingConfigure headSettingConfigure = HeadSettingConfigureParser.getHeadSettingConfigure(messageType);
		String encodeXmlData = message;
		if(isEncoded)
		   encodeXmlData = Base64EncodeUtil.encode(message);
		logger.info("wrap successed Filecount="+wrapSuccessCount.addAndGet(1) +" count="+getCount());
		return buildMessageWithHead(headSettingConfigure,encodeXmlData);
	}

	
	public File unWrap(String message) throws HeadUnWrapperException{
		File fileout = null;
		try {
			String result = doUnWrap(message);
			fileout = new File("oo.xml");
			BufferedWriter out = new BufferedWriter(new FileWriter(fileout));
			out.append(result).append("\n");
			out.flush();
			out.close();
		} catch (IOException e) {
			logger.error("HeadUnWraperImpl unWrapHead",e);
			throw new HeadUnWrapperException("" + e.getMessage());
		}
		return fileout;
	}
	
	private String buildMessageWithHead(HeadSettingConfigure headSettingConfigure, String encodeXmlData) {
		String receiverxml = "";
		for (int i = 0; i < headSettingConfigure.getReceiveIds().size(); i++) {
			String receiveid = headSettingConfigure.getReceiveIds().get(i);

			receiverxml = receiverxml + "\t\t\t<dxp:Id>" + receiveid
					+ "</dxp:Id>\n";
		}
		
		String keysxml = "";
		for (int i = 0; i < headSettingConfigure.getKeyNames().size(); i++) {
			
			String name = headSettingConfigure.getKeyNames().get(i);

			keysxml = keysxml + "\t\t\t<dxp:Key Name=\"" + name + "\"/>\n";
		}
		String completexml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        		+ "<dxp:DxpMsgCl ver=\"1.0\" xsi:schemaLocation=\"http://www.chinaport.gov.cn/Dxp DXP.xsd\" xmlns:dxp=\"http://www.chinaport.gov.cn/Dxp\" xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n"
				+ "\t<dxp:ClNo>\n" + "\t\t<dxp:SendId>"
				+ headSettingConfigure.getSendId()
				+ "</dxp:SendId>\n"
				+ "\t\t<dxp:Receivers>\n"
				+ receiverxml
				+ "\t\t</dxp:Receivers>\n"
				+ "\t\t<dxp:FileName></dxp:FileName>\n"
				+ "\t\t<dxp:CopMsgId></dxp:CopMsgId>\n"
				+ "\t\t<dxp:CreatTime>"
				+ headSettingConfigure.getCreatTime()
				+ "</dxp:CreatTime>\n"
				+ "\t\t<dxp:Type>"
				+ headSettingConfigure.getType()
				+ "</dxp:Type>\n"
				+ "\t\t<dxp:BizKey>\n"
				+ "\t\t\t<dxp:Key name=\"\"/>\n" 
				+ "\t\t</dxp:BizKey>\n"
				+ "\t\t<dxp:IsText Encode=\""
				+ headSettingConfigure.getIsText()
				+ "\"/>\n"
				+ "\t\t<dxp:RecMapId></dxp:RecMapId>\n"
				+ "\t\t<dxp:Compress>\n"
				+ "\t\t\t<dxp:Flag>"
				+ headSettingConfigure.getCompressFlag()
				+ "</dxp:Flag>\n"
				+ "\t\t\t<dxp:Type>"
				+ headSettingConfigure.getCompressType()
				+ "</dxp:Type>\n"
				+ "\t\t</dxp:Compress>\n"
				+ "\t</dxp:ClNo>\n"
				+ "\t<dxp:Data>"
				+ encodeXmlData
				+ "</dxp:Data>\n" + "</dxp:DxpMsgCl>";
		return completexml;
	}
	
	
	private String doUnWrap(String xml){
		String completexml = xml;
		try {
			Document document = XmlParseUtil.stringToDoc(xml);
			String root = document.getFirstChild().getNodeName();
			if ("dxp:DxpMsgCl".equals(root)) {
				Node data = XPathAPI.selectSingleNode(document,
						"//dxp:DxpMsgCl/dxp:Data");
				 completexml = data.getFirstChild().getTextContent();
				if(isEncoded){
					completexml = Base64EncodeUtil.deCode(completexml);
				}
				
			}
		} catch (Exception e) {
			logger.error("unWrap failed Filecount="+unWrapFailureCount.addAndGet(1),e);
			throw new HeadUnWrapperException("文件解掉传输头发生错误："+e.getMessage(),e);
		}
		logger.info("unWrap successed Filecount="+unWrapSuccessCount.addAndGet(1));
		
		return completexml;
	}

	int getCount(){
		if(count.get()==null){
			count.set(new Integer(0));
		}
		count.set(count.get()+1);
		return count.get().intValue();
	}

	
	public boolean isEncoded() {
		return isEncoded;
	}


	
	public void setEncoded(boolean isEncoded) {
		this.isEncoded = isEncoded;
	}


	
	public void setMessageType(String messageType) {
		this.messageType = messageType;
	}

}
